# -*- coding: utf-8 -*-
import datetime
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import utc_to_local_str

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '1918210173': {  # dwc 长盛支付 50--50000 支付宝 2。5%
        'API_KEY': 'fbf2df4a81d25f0caf173c5a082064e5',
        'gateway': 'http://yccp368.com/pay',
        'query_gateway': 'http://yccp368.com/pay/query',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _get_pay_type(service):
    if service == 'alipay':
        return 'alipay_bank2'
    return 'alipay_bank2'


def generate_sign(parameter, api_key):
    '''  生成下单签名 '''
    for key in parameter.keys():
        if not parameter.get(key):
            del parameter[key]
    s = ''
    for k in sorted(parameter.keys()):
        s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % api_key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("changshengpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _build_form(params):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + _get_gateway(
        params['merchant']) + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')
    pay_type = _get_pay_type(service)

    parameter_dict = OrderedDict((
        ('merchant', app_id),
        ('amount', '%.2f' % pay_amount),
        ('pay_code', pay_type),
        ('order_no', str(pay.id)),
        ('notify_url',
         '{}/pay/api/{}/changshengpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, str(app_id))),
        ('return_url', '{}/pay/api/{}/changshengpay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, app_id)),
        ('attach', 'recharge'),
        ('cuid', ''),
        ('order_time', utc_to_local_str(datetime.datetime.now())),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("changshengpay create  data: %s, url: %s", json.dumps(parameter_dict), _get_gateway(app_id))
    html_text = _build_form(parameter_dict)
    cache_id = redis_cache.save_html(pay.id, html_text)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("changshengpay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['out_order_no']
    if not pay_id:
        _LOGGER.error("changshengpay fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('changshengpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('changshengpay pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('changshengpay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = 'success'
    trade_no = data['out_order_no']
    total_fee = float(data['realPrice'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    _LOGGER.info('changshengpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
    order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
    # async notify
    async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('merchant', app_id),
        ('out_order_no', str(pay_order.id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("changshengpay query data: %s, order_id is: %s ", parameter_dict, parameter_dict['out_order_no'])
    url = _get_query_gateway(app_id).format(parameter_dict['merchant'], parameter_dict['out_order_no'], parameter_dict['sign'])
    _LOGGER.info("changshengpay query: url: %s", url)
    response = requests.get(url)
    _LOGGER.info("changshengpay query  rsp data: %s,%s", response.text, response.url)
    if response.status_code == 200:
        data = json.loads(response.text)
        code = str(data['respCode'])
        if code == '0000':
            mch_id = pay_order.mch_id
            trade_status = str(data['status'])
            total_fee = float(data['money'])
            trade_no = data['out_order_no']

            extend = {
                'trade_status': trade_status,
                'total_fee': total_fee,
                'trade_no': trade_no,
            }

            # 2：支付异常 1：支付成功 0：未支付 ;其他：用户还未完成支付或者支付失败
            if trade_status == '1':
                _LOGGER.info('changshengpay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
                order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                         total_fee, trade_no, extend)

                async_job.notify_mch(pay_order.id)
